﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PayexpDAL;

namespace Moneymatters
{
    public partial class TransactionTypeTreeViewForm : Form
    {
        List<TransactionType> transactionTypeList = null;
        string selectedFullText = string.Empty;
        string selectedShortText = string.Empty;
        List<TransactionType> selectedTransactionTypeList = new List<TransactionType>();

        ContextMenu contextMenu = new ContextMenu();
        MenuItem editNode = new MenuItem();
        MenuItem deleteNode = new MenuItem();
        MenuItem addChildNode = new MenuItem();
        
        bool _isBankTransactionOnly;
        bool _isMasterDataAddMode;

        public TransactionTypeTreeViewForm(bool isBankTransactionOnly, bool isMasterDataAddMode)
        {
            InitializeComponent();
            this.treeViewTransTypes.AfterSelect += treeViewTransTypes_AfterSelect;
            this.treeViewTransTypes.AfterLabelEdit += treeViewTransTypes_AfterLabelEdit; 
            //this.treeViewTransTypes

            this.label1.Text = string.Empty;
            
            editNode.Name = "edit";
            editNode.Text = "Edit";
            editNode.Click += editNode_Click;

            deleteNode.Name = "delete";
            deleteNode.Text = "Delete";
            deleteNode.Click += deleteNode_Click;

            addChildNode.Name = "addChildren";
            addChildNode.Text = "Add Children";
            addChildNode.Click += addChildNode_Click;

            contextMenu.MenuItems.Add(addChildNode);
            contextMenu.MenuItems.Add(editNode);
            contextMenu.MenuItems.Add(deleteNode);

            this._isBankTransactionOnly = isBankTransactionOnly;
            this._isMasterDataAddMode = isMasterDataAddMode;
        }

        void treeViewTransTypes_Leave(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        void treeViewTransTypes_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            this.BeginInvoke(new Action(() => afterAfterEdit(e.Node)));
        }

        private void afterAfterEdit(TreeNode node)
        {
            this.treeViewTransTypes.SelectedNode.EndEdit(false);

            if (string.IsNullOrEmpty(this.treeViewTransTypes.SelectedNode.Text.Trim()))
            {
                this.treeViewTransTypes.SelectedNode.Text = selectedShortText;
                this.treeViewTransTypes.SelectedNode.EndEdit(true);
            }
            else
            {
                this.treeViewTransTypes.SelectedNode.EndEdit(false);
            }
        }


        void addChildNode_Click(object sender, EventArgs e)
        {
            
        }

        void deleteNode_Click(object sender, EventArgs e)
        {
            
        }

        void editNode_Click(object sender, EventArgs e)
        {
            this.treeViewTransTypes.SelectedNode.BeginEdit();
        }

        void treeViewTransTypes_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode selectedNode = this.treeViewTransTypes.SelectedNode;
            //if (selectedNode.Text.Equals("Transaction Types"))
            if (selectedNode.Equals(this.treeViewTransTypes.Nodes[0]))
            {
                selectedFullText = string.Empty;
                selectedShortText = string.Empty;
                selectedTransactionTypeList.Clear();
                return;
            }

            TransactionType selectedTransactionType = (TransactionType)selectedNode.Tag;
            selectedTransactionTypeList.Clear();
            selectedTransactionTypeList.Add(selectedTransactionType);
            GetParentRecursively(selectedTransactionType);

            selectedTransactionTypeList.Reverse();
            selectedTransactionTypeList.RemoveAt(0);
            if (selectedTransactionTypeList.Count > 0)
            {
                selectedFullText = string.Join("-->", selectedTransactionTypeList.Select(t => t.Name).ToArray());
                selectedShortText = selectedTransactionTypeList.Last().Name;
            }

            this.label1.Text = selectedFullText;
        }

        public string GetSelectedFullText()
        {
            return selectedFullText;
        }

        public string GetSelectedShortText()
        {
            return selectedShortText;
        }

        public List<TransactionType> GetSelectedTransactionTypes()
        {
            return selectedTransactionTypeList;
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            
            if (this._isMasterDataAddMode)
            {
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
                return;
            }

            bool leadNodeSelected = false;
            if (this.selectedTransactionTypeList.Count == 0)
            {
                return;
            }
            else
            {
                TransactionType selectedLeafTransactionType = this.selectedTransactionTypeList[this.selectedTransactionTypeList.Count - 1];
                if (!this.transactionTypeList.Any(t => t.ParentId.Equals(selectedLeafTransactionType.Id)))
                {
                    leadNodeSelected = true;
                }
            }
            
            //if (this.selectedTransactionTypeList.Count < 2)
            //{
            //    MessageBox.Show("Please choose a valid head other than the root, Income and Expense.", "Improper Selection", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    this.selectedTransactionTypeList.Clear();
            //    this.DialogResult = System.Windows.Forms.DialogResult.Retry;
            //}
            if(!leadNodeSelected)
            {
                MessageBox.Show("Please choose a valid leaf node. If one does not exist to suit your purpose, please first add it to the master list and then make the transaction entry.", "Improper Selection", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.selectedTransactionTypeList.Clear();
                this.DialogResult = System.Windows.Forms.DialogResult.Retry;
            }
            else if (this._isBankTransactionOnly)
            {
                if (!this.selectedTransactionTypeList[1].Name.ToLower().Equals("bank"))
                {
                    MessageBox.Show("Please select a proper brank sub heading only.", "Improper Selection", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.selectedTransactionTypeList.Clear();
                    this.DialogResult = System.Windows.Forms.DialogResult.Retry;
                    //return;
                }
                else
                {
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                    this.Close();
                }
            }
            else if (this.selectedTransactionTypeList.Count > 1 && this.selectedTransactionTypeList[1].Name.ToLower().Equals("bank"))
            {
                MessageBox.Show("Please select a proper sub heading. What you have selected requires the transaction mode to be either Bank Credit or Bank Debit.", "Improper Selection", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.selectedTransactionTypeList.Clear();
                this.DialogResult = System.Windows.Forms.DialogResult.Retry;
                //return;
            }
            else
            {
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
        }

        private void GetParentRecursively(TransactionType currentNode)
        {
            TransactionType parentNode = transactionTypeList.Where(t => t.Id == currentNode.ParentId).FirstOrDefault();
            if (parentNode != null)
            {
                selectedTransactionTypeList .Add(parentNode);
                GetParentRecursively(parentNode);
            }
        }

        public void CreateTreeView(List<string> subTreeListToInclude)
        {
            transactionTypeList = new DataAccessHandler().GetAllTransactionTypeList(MainForm.Context);
            TransactionType rootTransType = transactionTypeList.Where(t => t.ParentId.Equals(-1)).FirstOrDefault();
            TreeNode rootNode = new TreeNode(rootTransType.Name);
            rootNode.Tag = rootTransType;
            this.treeViewTransTypes.Nodes.Add(rootNode);

            foreach (TransactionType transactionType in transactionTypeList.Where(t => t.ParentId == rootTransType.Id))
            {
                if (subTreeListToInclude.Count > 0 && !subTreeListToInclude.Contains(transactionType.Name.ToLower()))
                {
                    continue;
                }
                else
                {
                    TreeNode topNode = new TreeNode(transactionType.Name);
                    topNode.Tag = transactionType;
                    rootNode.Nodes.Add(topNode);
                    BuildTreeRecursively(topNode, transactionTypeList);
                }
            }

            rootNode.Expand();
            foreach (TreeNode childNode in rootNode.Nodes)
            {
                childNode.Expand();
            }
        }



        private void BuildTreeRecursively(TreeNode parentNode, List<TransactionType> transactionTypeList)
        {
            TransactionType currentTransactionType = (TransactionType)parentNode.Tag;
            foreach (TransactionType transactionType in transactionTypeList.Where(t => t.ParentId == currentTransactionType.Id))
            {
                TreeNode childNode = new TreeNode(transactionType.Name);
                childNode.Tag = transactionType;
                parentNode.Nodes.Add(childNode);
                BuildTreeRecursively(childNode, transactionTypeList);

                childNode.ContextMenu = this.contextMenu;
            }
        }
    }
}
